package org.lex.explorer.file;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.io.File;

public class DesktopAction extends AbstractFileAction {
	private boolean supported = true;
	private Desktop.Action action = null;

	public DesktopAction(FileExplorer fileExplorer, Desktop.Action action) {
		super(fileExplorer);
		this.action = action;
		this.setName(this.getName(action));
		if (false == Desktop.isDesktopSupported()) {
			supported = false;
			return;
		} else {
			if (false == Desktop.getDesktop().isSupported(action))
				supported = false;
		}
	}

	private String getName(Desktop.Action action) {
		String name = action.name().substring(1).toLowerCase();
		return action.name().substring(0, 1) + name;
	}

	public void setEnabled(boolean newValue) {
		if (false == this.supported)
			return;
		else
			super.setEnabled(newValue);
	}

	public void doInBackground(ActionEvent e) {
		File file = this.fileExplorer.getSelectedFile();
		if (null == file)
			return;
		try {
			Desktop desktop = Desktop.getDesktop();
			switch (action) {
			case EDIT:
				desktop.edit(file);
				break;
			case OPEN:
				desktop.open(file);
				break;
			case PRINT:
				desktop.print(file);
				break;
			default:
				this.message("Operation failed", action.name() + " not implement.");
				break;
			}
		} catch (Exception ex) {
			this.error("Operation failed", ex.getLocalizedMessage());
		}
	}
}
